<?php

namespace App\Services\MiaoSha;

use App\Input\MiaoInput;
use App\Models\MiaoSha\GoodsModel;
use App\Models\MiaoSha\MiaoModel;
use App\Models\MiaoSha\OrderModel;
use App\Services\BaseServices;
use Illuminate\Support\Facades\Redis;
use function DI\string;

class MiaoServies extends BaseServices
{
    public function getGoodsByGoodsId($goodsId)
    {
        return GoodsModel::query()->where("id", $goodsId)->first();
    }

    public function insMiao($data = null):int
    {
        return MiaoModel::query()->insertGetId($data);
    }

    /**
     * 创建秒杀
     * @param  MiaoInput  $input
     * @return array
     */
    public function addRedisGoods(MiaoInput $input)
    {
        $goods = $this->getGoodsByGoodsId($input->goods_id);
        if (is_null($goods)) {
            return ["message" => "商品不存在", "code" => false];
        }

        if ($goods->inventory < $input->num) {
            return ["message" => "商品库存不够", "code" => false];
        }
        $miao = MiaoModel::query()->where('goods_id',$input->goods_id)->whereIn("type",[1,2])->get();
        if (count($miao->toArray()) > 0){
            return ["message" => "该商品正在或准备秒杀中", "code" => false];
        }
        $miaoModel = [];
        $miaoModel['goods_id'] = $goods->id;
        $miaoModel['num'] = $input->num;
        $miaoModel['price'] = $input->price;
        $miaoModel['start_time'] = $input->start_time;
        $miaoModel['end_time'] = $input->end_time;
        $miaoModel['type'] = 1;
        $miaoId = $this->insMiao($miaoModel);
        if (!$miaoId) {
            return ["message" => "秒杀创建失败", "code" => false];
        }
        $mNum = $goods->inventory - $input->num;
        $ret = $this->updGoods($goods->id, ["inventory" => $mNum, "update_time" => date("Y-m-d H:i:s", time())]);
        if (!$ret) {
            return ["message" => "库存更新失败", "code" => false];
        }
        for ($i = 0; $i < $input->num; $i++) {
            Redis::rpush("MiaoSha:{$miaoId}", json_encode($goods->toArray(), JSON_UNESCAPED_UNICODE));
        }
        $len = Redis::llen("MiaoSha:{$miaoId}");
        if ($len != $input->num) {
            return ["message" => "数量错误", "code" => false];
        }
        return ["message" => "创建成功", "code" => true];
    }

    public function getMiaoByMId($mId)
    {
        return MiaoModel::query()->where("id", $mId)->first();
    }

    /**
     * 秒杀结束
     * @param $mId
     * @return array
     */
    public function miaoEnd($mId)
    {
        $miao = $this->getMiaoByMId($mId);
        if (is_null($miao)) {
            return ["message" => "该秒杀不存在", "code" => false];
        }
        $new = time();
        if ($miao->toArray()["type"] == 3){
            return ["message" => "改秒杀已结束,请勿重复操作", "code" => false];
        }
//        if ($miao->toArray()["endTime"] > $new){
//            return ["message" => "秒杀未结束，不可关闭", "code" => false];
//        }
        $len = Redis::llen("MiaoSha:{$mId}");
        if ($len > 0) {
            $goods = $this->getGoodsByGoodsId($miao->goods_id);
            if (!is_null($goods)) {
                $inventory = $goods->inventory + $len;
                $ret = $this->updGoods($goods->id,
                    ["inventory" => $inventory, "update_time" => date("Y-m-d H:i:s", time())]);
                if (!$ret) {
                    return ["message" => "库存修改失败", "code" => false];
                }
            }
        }
        Redis::del("MiaoSha:{$mId}");
        $ret = MiaoModel::query()->where("id",$mId)->update(["type"=>3]);
        if (!$ret){
            return ["message" => "库存修改失败", "code" => false];
        }
        return ["message" => "库存修改失败", "code" => true];
    }

    public function updGoods($goodsId, $data = null)
    {
        $ret = GoodsModel::query()->where("id", $goodsId)->update($data);
        return $ret;
    }

    /**
     * 秒杀下单
     * @param $userId
     * @param $goodsId
     * @return array
     */
    public function miaoAddOrder($userId,$mId)
    {
//        $miao = $this->getMiaoByMId($mId);
//        if (is_null($miao)){
//            return ["message" => "秒杀活动不存在", "code" => false];
//        }
//        if($miao->toArray()["type"] != 2){
//            return ["message" => "秒杀活动未开始或存在异常", "code" => false];
//        }
        $len = Redis::llen("MiaoSha:{$mId}");
        if ($len <= 0) {
            return ["message" => "商品售空", "code" => false];
        }
        $goods = Redis::rpop("MiaoSha:{$mId}");
        $ret = $this->addOrder($userId,$mId);
        if (!$ret['code']){
            Redis::rpush("MiaoSha:{$mId}",$goods);
            return ["message"=>"创建订单失败","code"=>false];
        }
        return ["message"=>"下单成功","code"=>true];
    }

    /**
     * 生成订单
     * @param $userId
     * @param $mId
     * @return array
     */
    public function addOrder($userId,$mId)
    {
        $orderNumber = MiaoServies::getInstance()->generateOrderNumber($userId);
        $miao = $this->getMiaoByMId($mId);
        if (is_null($miao)){
            return ["message"=>"系统错误","code"=>false];
        }
        $OrderModel = new OrderModel();
        $OrderModel->goods_id = $miao->goods_id;
        $OrderModel->price = $miao->price;
        $OrderModel->order_number = $orderNumber;
        $OrderModel->type = 1;
        $OrderModel->add_time = time();
        if (!$OrderModel->save()){
            return ["message"=>"失败","code"=>false];
        }
        return ["message"=>"成功","code"=>true];
    }

    /**
     * 生成订单号
     * @param $userId
     * @return string
     */
    public function generateOrderNumber($userId):string
    {
        $date = date("Ymd",time());
        $one = substr($userId,0,2);
        $two = substr($userId,2,2);
        $throw = rand(10000,99999);
        return "{$date}{$one}{$throw}{$two}";
    }


}
